package com.czkevin.guicontrolsapi.builtin;

import com.czkevin.guicontrolsapi.Window;
import com.czkevin.guicontrolsapi.controls.ButtonControl;
import com.czkevin.guicontrolsapi.controls.LabelControl;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.ItemStack;
import com.czkevin.guicontrolsapi.HeadTools;

import java.util.function.Consumer;

public class AlertWindow extends Window {

    private final Consumer<Boolean> callback;

    private boolean selected = false;

    public AlertWindow(AlertType type, String title, String message) {
        this(type, title, message, null);
    }

    public AlertWindow(AlertType type, String title, String message, Consumer<Boolean> callback) {
        super(title, 8, 5);
        this.callback = callback;
        if(type == null) type = AlertType.NORMAL;
        LabelControl label = new LabelControl(type.icon,
            title, message
        );
        setControl(2, 1, label);
        ButtonControl buttonYes = new ButtonControl(
            HeadTools.HEAD_IRON_CHECK, "\u00a7a\u00a7lYES", "\u00a77Click to select. "
        );
        buttonYes.setHandler((h) -> setSelectionAndCloseAll(true));
        if(type.isQuestion()) {
            ButtonControl buttonNo = new ButtonControl(
                HeadTools.HEAD_IRON_CROSS, "\u00a7c\u00a7lNO", "\u00a77Click to select. "
            );
            buttonNo.setHandler((h) -> setSelectionAndCloseAll(false));
            setControl(2, 3, buttonYes);
            setControl(5, 3, buttonNo);
        } else {
            setControl(5, 3, buttonYes);
        }
    }

    private void setSelectionAndCloseAll(boolean s) {
        if(selected) return;
        selected = true;
        if(callback != null) callback.accept(s);
        closeAll();
        destroy();
    }

    @Override
    public void onOpenInternal(HumanEntity target) {

    }

    @Override
    protected boolean onCloseInternal(HumanEntity target) {
        if(callback != null && !selected) callback.accept(false);
        return true;
    }

    public enum AlertType {
        NORMAL(HeadTools.HEAD_IRON_SPEECH_BUBBLE, false),
        ATTENTION(HeadTools.HEAD_IRON_SPEECH_BUBBLE_ATTENTION, false),
        QUESTION(HeadTools.HEAD_IRON_SPEECH_BUBBLE_QUESTION, true)
        ;

        private final ItemStack icon;
        private final boolean question;

        AlertType(ItemStack icon, boolean question) {
            this.icon = icon;
            this.question = question;
        }

        public boolean isQuestion() {
            return question;
        }
    }
}
